/**
 * @file spaceship.c
 * @brief spawn, move, update and init struct_player
 * main hero of the game. Code about moving, drawing, initing the only ship
 */
/* Allegro */
#include <allegro5/base.h>
/* Standard */
#include <math.h>
#include <stdbool.h>
#include <stdio.h>
/* Project */
#include <blasteroids.h>
#include <graphics.h>
#include <spaceship.h>
#include <movement.h>
extern bool *keys;

void ship_update(Spaceship *s) {
  ship_move(s, forward);
  ship_check_pos(s);
  ship_draw(s);
  ship_speed(s, inertion);
}

void ship_check_pos(Spaceship *s) {
  ALLEGRO_DISPLAY *display = al_get_current_display();
  int width = al_get_display_width(display);
  int height = al_get_display_height(display);
  if (s->sx > width) {
    s->sx = 0;
  }
  if (s->sx < 0) {
    s->sx = width;
  }
  if (s->sy > height) {
    s->sy = 0;
  }
  if (s->sy < 0) {
    s->sy = height;
  }
}

void ship_init(Spaceship *s) {
  s->color = SHIP_COLOR;
  s->speed = SPEED_INIT;
  s->twist = 0.0f;
  s->heading = 0.0f;
  s->gone = false;
  s->accel = true;
  s->sx = al_get_display_width(al_get_current_display()) / 2.0f;
  s->sy = al_get_display_height(al_get_current_display()) / 2.0f;
}
void ship_speed(Spaceship *s, void (*change)(float*)) {
  if (keys[FW]) {
    change(&s->speed);
  }
  if (s->speed < SPEED_STOP && -s->speed > -SPEED_STOP && s->accel) {
    s->speed = 0.0f;
    s->accel = false;
  }
  change(&s->speed);
}
void ship_rotate(Spaceship *s, void (*direction)(float*)) {
  direction(&s->twist);
}
void ship_move(Spaceship *s, void (*direction)(float*, float*, float, float)) {
  float diff = 0.0f;
  s->twist = normolize(s->twist);
  s->heading = normolize(s->heading);
  diff = normolize(s->twist - s->heading);
  if (!s->accel) {
    s->heading = s->twist;
  }
  if (keys[FW]) {
    s->accel = true;
    s->heading += diff / SPEED_VECTOR_CHANGE;
    s->speed -= 0.85f * s->speed * (fabsf(diff) / SPEED_BRAKE_VECTOR);
  }
  direction(&s->sx, &s->sy, s->speed,s->heading);
}
